package com.hui.jwt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hui.jwt.mapper.UserMapper;
import com.hui.jwt.pojo.JwtUser;
import com.hui.jwt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @BelongsProject: SpringSecurity-jwt
 * @BelongsPackage: com.hui.jwt.service
 * @Author: HUI
 * @CreateTime: 2022-04-02 20:29
 * @Description:
 */

@Service
public class MyUserDetailService implements UserDetailsService {


    @Autowired
    private UserMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = mapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (ObjectUtils.isEmpty(user)) throw new RuntimeException("用户名不存在!");

        return new JwtUser(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList("user,ROLE_admin"));
    }
}
